<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="curDialogVisible"
      center
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeHandle"
    >
      <div :style="{ textAlign: 'center' }">
        <img v-if="type === 'image'" :src="url" :style="{ width: '500px' }">
      </div>
      <div
        v-if="type === 'pdf'"
        :style="{ height: '500px', overflowY: 'scroll' }"
      >
        <pdf v-for="i in numPages" :key="i" :src="urlPdf" :page="i" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pdf from 'vue-pdf/src/vuePdfNoSssNoWorker'
import { isTypePdfOrImg } from '@/utils/tools'

export default {
  name: 'BlockDialog',
  components: { pdf },
  props: {
    url: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      curDialogVisible: true,
      numPages: 1,
      urlPdf: '',
      type: ''
    }
  },
  computed: {},
  mounted() {
    this.type = isTypePdfOrImg(this.name)
    this.type === 'pdf' && this.getNumPages(
      this.url
    )
  },
  methods: {
    async getNumPages(url) {
      const loadingTask = await pdf.createLoadingTask(url)
      loadingTask.promise
        .then((pdf) => {
          this.urlPdf = loadingTask
          this.numPages = pdf.numPages
        })
        .catch((err) => {
          console.error(err)
        })
    },
    closeHandle() {
      this.$emit('close')
    }
  }
}
</script>
<style scoped></style>
